<template>
  <div class="profile-container">
    <!-- Sidebar: Subject List -->
    <div class="sidebar">
      <div class="sidebar-header">
        <div class="title">人物档案</div>
        <div class="subtitle">共 {{ profiles.length }} 人</div>
      </div>
      
      <!-- Tabs -->
      <div class="entity-tabs">
        <button 
          :class="{ active: entityType === 'person' }" 
          @click="entityType = 'person'; loadProfiles()"
        >
          👤 个人
        </button>
        <button 
          :class="{ active: entityType === 'company' }" 
          @click="entityType = 'company'; loadProfiles()"
        >
          🏢 企业
        </button>
      </div>
      
      <div class="search-box">
        <input v-model="searchQuery" placeholder="搜索姓名/身份证/手机号..." @input="handleSearch" />
      </div>

      <div class="subject-list">
        <div v-if="loading" class="loading-state">加载中...</div>
        <div v-else-if="profiles.length === 0" class="empty-list">暂无档案数据</div>
        <div 
          v-else
          v-for="profile in profiles" 
          :key="profile.id" 
          class="subject-item"
          :class="{ active: currentProfileId === profile.id }"
          @click="selectProfile(profile.id)"
        >
          <div class="avatar">{{ entityType === 'person' ? '👤' : '🏢' }}</div>
          <div class="info">
            <div class="name">{{ profile.name || '未知' }}</div>
            <div class="id-card" v-if="profile.id_card">{{ maskIdCard(profile.id_card) }}</div>
            <div class="id-card" v-else-if="profile.credit_code">{{ profile.credit_code }}</div>
            <div class="meta">
              <span v-if="profile.phones?.length">📱 {{ profile.phones.length }}</span>
              <span v-if="profile.accounts?.length">💳 {{ profile.accounts.length }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Pagination -->
      <div class="pagination" v-if="total > pageSize">
        <button @click="prevPage" :disabled="page <= 1">上一页</button>
        <span>{{ page }} / {{ Math.ceil(total / pageSize) }}</span>
        <button @click="nextPage" :disabled="page >= Math.ceil(total / pageSize)">下一页</button>
      </div>
    </div>

    <!-- Main Content: Profile Details -->
    <main class="main-content">
      <div v-if="currentProfile" class="profile-detail">
        <!-- Header -->
        <div class="detail-header">
          <div class="header-avatar">{{ currentProfile.entity_type === 'person' ? '👤' : '🏢' }}</div>
          <div class="header-info">
            <h1>{{ currentProfile.name || '未知' }}</h1>
            <div class="tags">
              <span class="tag" v-if="currentProfile.id_card">🆔 {{ currentProfile.id_card }}</span>
              <span class="tag" v-if="currentProfile.credit_code">🏢 {{ currentProfile.credit_code }}</span>
              <span class="tag gender-tag" v-if="currentProfile.gender">
                {{ currentProfile.gender === '男' ? '♂' : '♀' }} {{ currentProfile.gender }}
              </span>
              <span class="tag" v-if="currentProfile.birth_date">🎂 {{ currentProfile.birth_date }}</span>
              <span class="tag" v-if="currentProfile.province">📍 {{ currentProfile.province }}</span>
            </div>
          </div>
        </div>

        <!-- Tabs Navigation -->
        <div class="profile-tabs">
            <button class="tab-btn" :class="{ active: currentTab === 'info' }" @click="currentTab = 'info'">基础信息</button>
            <button class="tab-btn" :class="{ active: currentTab === 'graph' }" @click="currentTab = 'graph'">关系网络</button>
            <button class="tab-btn" :class="{ active: currentTab === 'timeline' }" @click="currentTab = 'timeline'">时间轨迹</button>
        </div>

        <!-- Cards Grid (Info Tab) -->
        <div class="cards-grid" v-if="currentTab === 'info'">
          <!-- Phone Numbers -->
          <div class="info-card">
            <div class="card-title">
              <span>📱 关联手机</span>
              <span class="count">{{ currentProfile.phones?.length || 0 }}</span>
            </div>
            <div class="card-body">
              <div v-if="!currentProfile.phones?.length" class="empty-text">无记录</div>
              <div v-else class="account-list">
                <div v-for="phone in currentProfile.phones" :key="phone" class="account-item">
                  <span class="acc-icon">📞</span>
                  <span class="acc-number">{{ phone }}</span>
                  <button class="btn-copy" @click="copyText(phone)" title="复制">📋</button>
                </div>
              </div>
            </div>
          </div>

          <!-- Bank Accounts -->
          <div class="info-card">
            <div class="card-title">
              <span>💳 银行账户</span>
              <span class="count">{{ currentProfile.accounts?.length || 0 }}</span>
            </div>
            <div class="card-body">
              <div v-if="!currentProfile.accounts?.length" class="empty-text">无记录</div>
              <div v-else class="account-list">
                <div v-for="acc in currentProfile.accounts" :key="acc" class="account-item">
                  <span class="acc-icon">🏦</span>
                  <span class="acc-number">{{ acc }}</span>
                  <button class="btn-copy" @click="copyText(acc)" title="复制">📋</button>
                </div>
              </div>
            </div>
          </div>

          <!-- Addresses -->
          <div class="info-card" v-if="currentProfile.addresses?.length">
            <div class="card-title">
              <span>🏠 关联地址</span>
              <span class="count">{{ currentProfile.addresses?.length || 0 }}</span>
            </div>
            <div class="card-body">
              <div class="account-list">
                <div v-for="addr in currentProfile.addresses" :key="addr" class="account-item">
                  <span class="acc-icon">📍</span>
                  <span class="acc-number">{{ addr }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Relationship Graph Tab -->
        <div v-else-if="currentTab === 'graph'" class="tab-content">
            <RelationshipGraph :data="graphData" />
        </div>

        <!-- Timeline Tab -->
        <div v-else-if="currentTab === 'timeline'" class="tab-content">
            <Timeline :events="timelineData" />
        </div>
        
        <!-- Linked Data Stats -->
        <div class="stats-section" v-if="Object.keys(currentProfile.linked_data || {}).length">
          <h3>📊 关联数据统计</h3>
          <div class="stats-grid">
            <div v-for="(count, table) in currentProfile.linked_data" :key="table" class="stat-item">
              <div class="stat-label">{{ getTableDisplayName(table) }}</div>
              <div class="stat-value">{{ count }} 条</div>
            </div>
          </div>
        </div>

        <!-- Extra Data -->
        <div class="extra-section" v-if="currentProfile.extra_data && Object.keys(currentProfile.extra_data).length">
          <h3>📋 扩展信息</h3>
          <div class="extra-grid">
            <div v-for="(value, key) in currentProfile.extra_data" :key="key" class="extra-item">
              <span class="extra-label">{{ key }}</span>
              <span class="extra-value">{{ value }}</span>
            </div>
          </div>
        </div>

      </div>

      <div v-else class="empty-state">
        <div class="empty-icon">👤</div>
        <h3>请选择左侧人员查看画像</h3>
        <p class="empty-hint" v-if="profiles.length === 0">
          尚未导入人物档案数据<br />
          请先导入公安个人信息或廉政档案
        </p>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import RelationshipGraph from './components/RelationshipGraph.vue'
import Timeline from './components/Timeline.vue'

const route = useRoute()
const profiles = ref([])
const currentProfileId = ref(null)
const currentProfile = ref(null)
const searchQuery = ref('')
const loading = ref(false)
const entityType = ref('person')
const currentTab = ref('info')
const page = ref(1)
const pageSize = ref(20)
const total = ref(0)

// Graph & Timeline Data
const graphData = ref({ nodes: [], edges: [] })
const timelineData = ref([])

// Load profiles list
const loadProfiles = async () => {
  const caseId = route.query.caseId
  if (!caseId) return
  
  loading.value = true
  try {
    const result = await window.electronAPI.profile.list(
      caseId, 
      page.value, 
      pageSize.value, 
      entityType.value
    )
    if (result.success) {
      profiles.value = result.items
      total.value = result.total
      
      // Auto-select first if available
      if (profiles.value.length > 0 && !currentProfileId.value) {
        selectProfile(profiles.value[0].id)
      }
    }
  } catch (e) {
    console.error('Failed to load profiles', e)
  } finally {
    loading.value = false
  }
}

// Search profiles
const handleSearch = async () => {
  const caseId = route.query.caseId
  if (!caseId) return
  
  if (!searchQuery.value) {
    loadProfiles()
    return
  }
  
  loading.value = true
  try {
    const result = await window.electronAPI.profile.search(caseId, searchQuery.value, {
      entity_type: entityType.value
    })
    if (result.success) {
      profiles.value = result.items
      total.value = result.total
    }
  } catch (e) {
    console.error('Failed to search profiles', e)
  } finally {
    loading.value = false
  }
}

// Select a profile
const selectProfile = async (id) => {
  currentProfileId.value = id
  const caseId = route.query.caseId
  if (!caseId) return
  
  try {
    const result = await window.electronAPI.profile.get(caseId, id)
    if (result.success) {
      currentProfile.value = result.data
      loadExtraData(id)
    }
  } catch (e) {
    console.error('Failed to get profile', e)
  }
}

const loadExtraData = async (id) => {
  const caseId = route.query.caseId
  if (!caseId) return

  try {
      // Load Graph Data
      const graphRes = await window.electronAPI.profile.getGraph(caseId)
      graphData.value = graphRes

      // Load Timeline Data
      const profile = profiles.value.find(p => p.id === id)
      if (profile) {
            let identifier = profile.id_card || (profile.phones && profile.phones[0])
            if (identifier) {
                const timelineRes = await window.electronAPI.profile.getTimeline({ 
                  caseId, 
                  identifier 
                })
                timelineData.value = timelineRes
            }
      }
  } catch (e) {
      console.error("Failed to load extra data", e)
  }
}

// Pagination
const prevPage = () => {
  if (page.value > 1) {
    page.value--
    loadProfiles()
  }
}

const nextPage = () => {
  if (page.value < Math.ceil(total.value / pageSize.value)) {
    page.value++
    loadProfiles()
  }
}

// Utilities
const copyText = (text) => {
  navigator.clipboard.writeText(text)
}

const maskIdCard = (idCard) => {
  if (!idCard || idCard.length < 8) return idCard
  return idCard.substring(0, 6) + '****' + idCard.substring(idCard.length - 4)
}

const getTableDisplayName = (table) => {
  const names = {
    'bank_transactions': '💰 银行流水',
    'call_records': '📞 通话记录',
    'travel_records': '🚄 出行记录',
    'hotel_records': '🏨 住宿记录',
    'vehicle_records': '🚗 车辆信息',
    'company_records': '🏢 工商登记',
    'property_records': '🏠 不动产',
  }
  return names[table] || table
}

onMounted(() => {
  loadProfiles()
})

// Watch for route changes
watch(() => route.query.caseId, () => {
  profiles.value = []
  currentProfileId.value = null
  currentProfile.value = null
  page.value = 1
  loadProfiles()
})
</script>

<style scoped>
.profile-container {
  display: flex;
  height: 100%;
  background: #f5f7fa;
}

.sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e6e6e6;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.subtitle {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.entity-tabs {
  display: flex;
  padding: 10px;
  gap: 5px;
  border-bottom: 1px solid #f0f0f0;
}

.entity-tabs button {
  flex: 1;
  padding: 8px;
  border: 1px solid #dcdfe6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.entity-tabs button.active {
  background: #409eff;
  color: white;
  border-color: #409eff;
}

.search-box {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.search-box input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 13px;
}

/* Profile Tabs */
.profile-tabs {
    display: flex;
    gap: 15px;
    margin-bottom: 20px;
    border-bottom: 1px solid #e4e7ed;
    padding-bottom: 0px;
}

.tab-btn {
    padding: 10px 20px;
    border: none;
    background: none;
    font-size: 15px;
    color: #606266;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    transition: all 0.3s;
}

.tab-btn.active {
    color: #409EFF;
    border-bottom-color: #409EFF;
    font-weight: 500;
}

.tab-btn:hover {
    color: #409EFF;
}

.tab-content {
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(5px); }
    to { opacity: 1; transform: translateY(0); }
}

.subject-list {
  flex: 1;
  overflow-y: auto;
}

.loading-state,
.empty-list {
  padding: 40px 20px;
  text-align: center;
  color: #909399;
}

.subject-item {
  display: flex;
  padding: 15px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
  transition: background 0.2s;
}

.subject-item:hover {
  background: #f5f7fa;
}

.subject-item.active {
  background: #ecf5ff;
  border-right: 3px solid #409eff;
}

.avatar {
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 12px;
}

.info {
  flex: 1;
  overflow: hidden;
}

.name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.id-card {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
  font-family: monospace;
}

.meta {
  font-size: 12px;
  color: #c0c4cc;
  display: flex;
  gap: 10px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  padding: 15px;
  border-top: 1px solid #f0f0f0;
}

.pagination button {
  padding: 5px 12px;
  border: 1px solid #dcdfe6;
  background: white;
  border-radius: 4px;
  cursor: pointer;
}

.pagination button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.main-content {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.profile-detail {
  max-width: 1000px;
  margin: 0 auto;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.header-avatar {
  width: 80px;
  height: 80px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 40px;
  margin-right: 25px;
}

.header-info h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #303133;
}

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag {
  background: #f4f4f5;
  color: #909399;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 13px;
}

.gender-tag {
  background: #e6f7ff;
  color: #1890ff;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.info-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  overflow: hidden;
}

.card-title {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  color: #303133;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.count {
  background: #f0f2f5;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: #909399;
}

.card-body {
  padding: 0;
  max-height: 250px;
  overflow-y: auto;
}

.account-list {
  display: flex;
  flex-direction: column;
}

.account-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  border-bottom: 1px solid #f5f7fa;
}

.account-item:last-child {
  border-bottom: none;
}

.acc-icon {
  margin-right: 10px;
  font-size: 16px;
}

.acc-number {
  flex: 1;
  font-family: monospace;
  color: #606266;
}

.btn-copy {
  border: none;
  background: none;
  cursor: pointer;
  opacity: 0.5;
  transition: opacity 0.2s;
}

.btn-copy:hover {
  opacity: 1;
}

.empty-text {
  padding: 20px;
  text-align: center;
  color: #c0c4cc;
}

.stats-section,
.extra-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.stats-section h3,
.extra-section h3 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #303133;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
}

.stat-item {
  background: #f9fafc;
  padding: 15px;
  border-radius: 6px;
  text-align: center;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.extra-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 10px;
}

.extra-item {
  display: flex;
  padding: 8px;
  background: #f9fafc;
  border-radius: 4px;
}

.extra-label {
  color: #909399;
  margin-right: 10px;
}

.extra-value {
  color: #303133;
  flex: 1;
}

.empty-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-hint {
  text-align: center;
  font-size: 13px;
  color: #c0c4cc;
  margin-top: 10px;
  line-height: 1.6;
}
</style>
